#!/usr/bin/python
# encoding: utf-8
import os
import MySQLdb
import sys
import shutil

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

chsipto = "/student/chsipto"
diffpto = "/student/diffpto"
edupto = "/student/edupto"
headpro = "/student/headpro"
idbackpto = "/student/idbackpto"
idfront = "/student/idfrontpto"

basepath = "/Users/konbluesky/eova/static"

cxn = MySQLdb.Connect(host='127.0.0.1', user='root', passwd='root',charset='utf8')

class PtoUtil:
    def dir_clean(self,dirpath,column):
        # 获取文件列表
        oldpath=basepath + dirpath
        filenames = os.listdir(oldpath)
        # 获取原目录文件总数
        oldcount = len(filenames)
        newcount = 0
        newdir=oldpath+"-无效/"

        if(not os.path.exists(newdir)):
            os.mkdir(newdir)

        for name in filenames:
            cur = cxn.cursor()
            cur.execute("use bstudy_sys")
            cur.execute("select * from student_enroll where %s='%s'" % (column,name))
            result=cur.fetchone()
            if(not result):
                # print result
                # print "找到相关记录 studentid:"+str(result[1])+"-"+result[2]
            # else:
                # print "未找到相关记录 文件名:"+name
                shutil.copy(oldpath+"/"+name,newdir+name)
                newcount+=1
                os.remove(oldpath+"/"+name)
            cur.close()

        print "原目录:"+oldpath +" 文件总数:"+str(oldcount)+"\n"
        print "无效文件:"+newdir +" 文件总数:"+str(newcount)+"\n"

if __name__ == "__main__":
    util = PtoUtil()
    util.dir_clean(chsipto,"chsipto")
    util.dir_clean(diffpto,"diffpto")
    util.dir_clean(edupto,"edupto")
    util.dir_clean(headpro,"headpto")
    util.dir_clean(idbackpto,"idbackpto")
    util.dir_clean(idfront,"idfrontpto")
